class_name Trigger
extends Node

## 参考自这个 https://github.com/JACKADUX/jackadux-godot-addons/tree/main/addons/handy_nodes/trigger_reactor

#region 属性
@export var trigger_node:Node
@export var trigger_types:Array[GameEnum.TriggerType]
## 是否在root节点Ready后执行一次
@export var trigger_on_ready:bool = false
var connect_obj_dict:Dictionary = {}
#endregion
#region 字段
#endregion
#region 信号
signal triggered(data:Dictionary)
#endregion

#region 基类方法
#endregion
#region 公共方法
func raise_trigger(data:Dictionary = {}):
	triggered.emit(data)
func connect_trigger(trigger_type:GameEnum.TriggerType):
	if not trigger_node:
		return
	match trigger_type:
		GameEnum.TriggerType.None:
			pass
		GameEnum.TriggerType.MOUSE_IN:
			if trigger_node is Control:
				connect_obj_dict[trigger_node.mouse_entered] = ConnectObj.new(trigger_node.mouse_entered,[raise_trigger])
		GameEnum.TriggerType.MOUSE_OUT:
			if trigger_node is Control:
				connect_obj_dict[trigger_node.mouse_exited] = ConnectObj.new(trigger_node.mouse_exited,[raise_trigger])
		GameEnum.TriggerType.PRESSED:
			if trigger_node is Control:
				connect_obj_dict["MousePressed"] = ConnectObj.new(trigger_node.gui_input,[func(event:InputEvent):
					if event is InputEventMouseButton and event.is_pressed():
						if event.button_index == MOUSE_BUTTON_LEFT :
							raise_trigger()]
					)
		GameEnum.TriggerType.RELEASED:
			if trigger_node is Control:
				connect_obj_dict["MouseReleased"] = ConnectObj.new(trigger_node.gui_input,[func(event:InputEvent):
					if event is InputEventMouseButton and event.is_released():
						if event.button_index == MOUSE_BUTTON_LEFT :
							raise_trigger()]
					)
		GameEnum.TriggerType.DOUBLE_CLICKED:
			if trigger_node is Control:
				connect_obj_dict["MousePressed"] = ConnectObj.new(trigger_node.gui_input,[func(event:InputEvent):
					if event is InputEventMouseButton :
						if event.double_click:
							raise_trigger()]
					)
		GameEnum.TriggerType.READY:
			connect_obj_dict[trigger_node.ready] = ConnectObj.new(trigger_node.ready,[raise_trigger])
		GameEnum.TriggerType.VISIBLITY_CHANGED:
			if trigger_node is CanvasItem:
				connect_obj_dict[trigger_node.visibility_changed] = ConnectObj.new(trigger_node.visibility_changed,[func():
					raise_trigger({"visible":trigger_node.is_visible_in_tree()})]
				)
		_:
			pass
#endregion
#region 私有方法
#endregion
#region 生命周期函数
func _ready() -> void:
	if not trigger_node:
		trigger_node = get_parent()
	for trigger_type in trigger_types:
		connect_trigger(trigger_type)
	if not get_tree().root.is_node_ready():
		await get_tree().root.ready
	if trigger_on_ready:
		raise_trigger()
func _notification(what: int) -> void:
	if what == NOTIFICATION_PREDELETE:
		for connect_obj:ConnectObj in connect_obj_dict.values():
			if connect_obj:
				connect_obj.disconnect_all()
#endregion
